<?php
namespace App\Repositories;

use Guzzle;
use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;
use Illuminate\Support\Facades\Config;

class JPushRepository extends EloquentRepository
{
	protected $options;
	protected $message;
	protected $platform;
	protected $audience;
	protected $sms_message;
	protected $notification;

	protected $tag;
	protected $tag_and;
	protected $alias;
	protected $registration_id;

	public function __construct()
	{

	}

	/**
	 * 生成秘钥
	 * @return string
	 */
	public function generator_basic_key()
	{
		$appKey = Config::get('jpush.app_key');
		$masterSecret = Config::get('jpush.master_secret');
		$basicKey = base64_encode("{$appKey}:{$masterSecret}");

		return $basicKey;
	}

	/**
	 * 获取push地址
	 * @return mixed
	 */
	public function get_push_url()
	{
		return Config::get('jpush.push_url');
	}

	/**
	 * platform    必填    推送平台设置
	 * audience    必填    推送设备指定
	 * notification    可选    通知内容体。是被推送到客户端的内容。与 message 一起二者必须有其一，可以二者并存
	 * message    可选    消息内容体。是被推送到客户端的内容。与 notification 一起二者必须有其一，可以二者并存
	 * sms_message    可选    短信业务功能
	 * options    可选    推送参数
	 * @param $platform
	 * @param $audience
	 * @param array $cond
	 */
	public function build($platform, $audience, $cond = [])
	{
		$build = [];
		/**
		 * 必选参数
		 */
		$build['platform'] = $platform;
		$build['audience'] = $audience;

		/**
		 * 可选参数
		 */
		if (isset($cond['notification'])) {
			$build['notification'] = $cond['notification'];
		}
		if (isset($cond['message'])) {
			$build['message'] = $cond['message'];
		}
		if (isset($cond['sms_message	'])) {
			$build['sms_message	'] = $cond['sms_message	'];
		}
		if (isset($cond['options'])) {
			$build['options'] = $cond['options'];
		}

		return json_encode($build);

	}

	/**
	 * @param $platform
	 * @param $audience
	 * @param array $cond
	 * @return \Psr\Http\Message\ResponseInterface|string
	 */
	public function push($platform, $audience, $cond = [])
	{
		/**
		 * 构造参数
		 */
		$data = $this->build($platform, $audience, $cond);
		$basicKey = $this->generator_basic_key();
		$url = $this->get_push_url();
		$headers = [
			'accept'        => 'application/json',
			'authorization' => "Basic {$basicKey}",
		];
		/**
		 * 推送消息到服务器
		 */
		try {
			$client = new Client();
			$result = $client->post($url, ['headers' => $headers, 'body' => $data]);
			$result = $result->getBody()->getContents();
		} catch (\GuzzleHttp\Exception\ClientException $exception) {
			/**
			 * 失败获取说明
			 */
			$result = $exception->getResponse()->getBody()->getContents();
		}

		return $result;
	}
}